
define(function (require, exports) {

    exports.ready = function (hashCode, data, cite) {
        yufp.custom.vue({
            el: cite.el,
            data: function () {
                var _this = this;
                /*定义校验规则，只能填字母数字 下划线*/
                var valiCodes = function (rule, value, callback) {
                    var reg = /^[0-9a-zA-Z_]{1,}$/;
                    if (value && reg.test(value)) {
                        if (value.length > 64) {
                            callback(new Error('长度不能大于64位'));
                        } else {
                            callback();
                        }
                    } else if (value && !reg.test(value)) {
                        callback(new Error('能填字母、数字和下划线'));
                    } else {
                        callback();
                    }
                };
                return {
                    rules: {
                        timerCode: [
                            { validator: valiCodes, trigger: 'blur' }
                        ],
                        expression: [
                            { required: true, message: '必填项', trigger: 'blur' }
                        ]
                    },
                    tbHeight: '0',
                    //导入导出的data  start
                    importFnButton: !yufp.session.checkCtrl('importFn'),
                    exportFnButton: !yufp.session.checkCtrl('exportFn'),
                    upLoadDialogVisible: false,//是否显示导入页面
                    upLoadUrl: yufp.service.getUrl({ url: "api/file/provider/uploadfile" }),//导入的url
                    appUploadDatas: [],//文件列表
                    showHeader: false,//是否显示错误表头
                    errshow: false,//显示导入的错误信息，默认不显示
                    excelloading: false,//导入的loading
                    errdata: [],//导入的错误信息
                    multipleFalg: false,//是否允许多文件
                    //导入导出的data  end

                    searchFormdata: {},
                    appNameDisabled: false,
                    addFnButton: !yufp.session.checkCtrl('addFn'),
                    updateFnButton: !yufp.session.checkCtrl('updateFn'),
                    deleteFnButton: !yufp.session.checkCtrl('deleteFn'),

                    treeDataUrl: "api/use/plats/apps/getTreeWftList",
                    dataUrl: 'api/use/plats/trigger/queryList',
                    formdata: {},
                    intervalTimeRule: [
                        { required: true, message: '必填项', trigger: 'blur' },
                        { validator: _this.checkTimeValidate, trigger: 'blur' }],
                    intervalDateTimeRule: [
                        { required: true, message: '必填项', trigger: 'blur' },
                        { validator: _this.checkDateTimeValidate, trigger: 'blur' }],
                    execMethod: [{ key: 'E', value: '固定时间' },
                    { key: 'I', value: '间隔时间' }],
                    isView: false,
                    expressReadOnly: true,
                    //disabeldone:false,//定义类型不可选择
                    addBtnShow: false,
                    async: false,
                    height: yufp.frame.size().height - 90,
                    dialogVisible: false,
                    formDisabled: false,
                    viewTitleArrry: ['触发器新增', '触发器修改', '触发器查看'],
                    viewTitle: '',
                    appCodeShow: true,
                    addFlag: false,
                    nodeLeaf: false,
                    currentClickNode: {},
                    isDisabledAppName: false,
                    isReadOnly: false,
                    isUdfFlag: false,
                    isExecInterValFlag: false,
                    isExpressionReadOnly: true,
                    execTimesArrays: [{ key: "11", value: "* * ? *", desc: "每天" },
                    { key: "31", value: "1,11,21 * ? *", desc: "旬初" },//旬初
                    { key: "41", value: "1 * ? *", desc: "月初" }, //月初
                    { key: "42", value: "L * ? *", desc: "月末" }, //月末
                    { key: "51", value: "1 1,4,7,10 ? *", desc: "季初" },//季初
                    { key: "52", value: "L 3,6,9,12 ? *", desc: "季末" },// 季末
                    { key: "61", value: "1 1 ? *", desc: "年初" },//年初
                    { key: "62", value: "L 6 ? *", desc: "半年末" },//半年末
                    { key: "63", value: "L 12 ? *", desc: "年末" }//年末
                    ],
                    exportLoading: false
                };
            },
            mounted: function () {
                var _this = this;
                //测试
                _this.$nextTick(function () {
                    var tableBox = _this.$refs.tableBox;
                    let a = tableBox.getBoundingClientRect().top + 28;
                    var theight = `calc(100vh - ${a}px - 64px)`;
                    _this.tbHeight = theight;
                });
            },
            methods: {
				//点击导出模板操作
				exportDemo: function(){
					var _this = this;
					var condition = {busiType:"TRIGGER"};
					var search = _this.searchFormdata;
					 yufp.util.download("api/use/excel/exportTempExcel?condition="
					  +  encodeURI(JSON.stringify(condition)));
				},
				//点击导出操作
				exportFlowFn: function() {
					var _this = this;
					var condition = {busiType:"TRIGGER"};
					var search = _this.searchFormdata;
					condition.appName = search.appName;
					condition.timerName = search.timerName;
					var selections = _this.$refs.refTable.selections ||[];
                    if (selections.length >0) {
                       condition.dataList = _this.$refs.refTable.selections;
                      }


                    _this.exportLoading = true;
                    yufp.service.request({
						  method: 'POST',
						  url: '/api/use/excel/exportExcelForWeb',
                        data: { condition: condition },
                        callback: function (code, message, response) {
                            _this.exportLoading = false;
                            if (response.code === 0) {
                                yufp.util.download("api/use/excel/downLoadExcel?filePath=" + response.data.allFilePath + "&fileName=" + response.data.fileName);
                            } else {
                                this.$message.error('导出失败');
                            }
                        }
                    });
                },
                importFlowFn: function () { //点击导入操作
                    this.upLoadDialogVisible = true;
                    this.$nextTick(function () {
                        this.$refs['my-upload'].clearFiles();
                        this.errshow = false;
                        this.errdata = [];
                    })
                },
				/**
				 *导入前的检验操作操作
				 */
                checkUpload: function (file) {
                    //alert(file);

                    var isLt10M = file.size / 1024 / 1024 < 100;
                    if (!isLt10M) {
                        this.$message.error('上传文件大小不能超过 100MB!');
                    }
                    var index = file.name.lastIndexOf('.');
                    var ext = file.name.substr(index + 1);

                    var suffixValid = ('xlsx' === ext || 'xls' === ext);
                    if (!suffixValid) {
                        this.$message.error('上传文件的格式必须为excel格式');
                        return false;
                    }
                    return isLt10M && suffixValid;
                },
                successUpload: function (response, file, fileList) { //导入成功后执行
					/*	console.log('上传成功！')
						this.$refs['my-upload'].clearFiles();*/


                    const _this = this;
                    const param = {};
					/* 					_this.$loading({
											target:'.load-target',
											body:true
										}) */
                    _this.excelloading = true;
                    param.busiType = "TRIGGER";
                    param.excelUpLoadFile = response.data;
                    yufp.service.request({
                        method: 'POST',
                        url: '/api/use/excel/importExcel',
                        data: param,
                        timeout: 1800000,
                        callback: function (code, message, response) {
                            _this.excelloading = false;
                            if (response.code == 0 && response.data.errorInfos.length == 0 && response.data.impStatus != '失败') {
                                _this.$refs['my-upload'].clearFiles();
                                _this.errshow = false;
                                _this.errdata = [];
                                _this.upLoadDialogVisible = false;
                                _this.$message('导入成功!');
                                //同时重新查询列表

                                var param = {
                                    condition: JSON.stringify(_this.searchFormdata)
                                };
                                _this.$refs.refTable.remoteData(param);

                            } else {
                                _this.errshow = true;
                                _this.$refs['my-upload'].clearFiles();
                                _this.errdata = [];
                                if (response.data && response.data.errorInfos.length > 0 && response.data.errorInfos[0].errorList) {
                                    response.data.errorInfos[0].errorList.map(function (item, index) {
                                        _this.errdata.push({
                                            "errMsg": item
                                        })
                                        console.log('errdata', _this.errdata)
                                    })
                                } else {
                                    _this.errdata.push({
                                        "errMsg": response.message
                                    })
                                }

                            }
                        }
                    });
                },

                reloadData: function () {
                    const _this = this;

                    var param = { condition: JSON.stringify(_this.searchFormdata) };

                    _this.$refs.refTable.remoteData(param);
                },

                /**
                 * 取消
                 */
                cancelFn: function () {
                    var _this = this;
                    _this.dialogVisible = false;
                },
                /**
                 * 保存
                 */
                saveFn: function () {
                    var _this = this;
                    var validate = false;
                    _this.$refs.refForm.validate(function (valid) {
                        validate = valid;
                    });
                    if (!validate) {
                        return;
                    }
                    if (_this.formdata.startTime != null && _this.formdata.startTime != '') {
                        if (_this.formdata.endTime != null && _this.formdata.endTime != '') {
                            if (_this.formdata.startTime > _this.formdata.endTime) {
                                _this.$message({ message: "开始日期不能大于结束日期", type: "warning" });
                                return;
                            }
                        }
                    }
                    var paramObj = _this.formdata;
                    paramObj.effectDate = _this.formdata.startTime;//_this.getStrFromDate(_this.formdata.startTime);
                    paramObj.expireDate = _this.formdata.endTime == undefined ? "" : _this.formdata.endTime;//_this.getStrFromDate(_this.formdata.endTime);
                    let urlparam = "";
                    if (_this.addFlag) {
                        urlparam = 'api/use/plats/trigger/addUseTaskTimer';
                    } else {
                        urlparam = 'api/use/plats/trigger/updateUseTaskTimer';
                    }
                    yufp.service.request({
                        method: 'POST',
                        url: urlparam,
                        data: paramObj,
                        callback: function (code, message, response) {
                            if (response.code == 0) {
                                _this.reloadData();
                                _this.$message('操作成功');
                                _this.dialogVisible = false;
                            } else {
                                _this.$message({ message: response.message, type: "warning" });
                            }
                        }
                    });
                },
                /**
                 * 控制保存按钮、xdialog、表单的状态
                 * @param viewType 表单类型
                 * @param editable 可编辑,默认false
                 */
                switchStatus: function (viewType, editable) {
                    var _this = this;
                    _this.viewType = viewType;
                    _this.dialogVisible = true;
                    _this.formDisabled = !editable;
                    _this.saveBtnShow = editable;
                    _this.cancelBtnShow = editable;
                },
                //改变定义类型
                changeMethod: function (val) {
                    console.log(val);
                    if ('1' == val) {
                        //手动
                        //触发执行频率的onchange事件
                        this.changeExecMethod(this.formdata.execMethod);
                        this.changeExecTimes(this.formdata.execTimes);
                    } else {
                        //自动
                    }

                },
                changeExecMethod: function (val) {
                    const _this = this;
                    if (val === 'I') {

                        if (_this.formdata.intervalTime == null || _this.formdata.intervalTime === '') {
                            _this.setExpressValue("INTERVAL", 0);
                        } else {
                            _this.setExpressValue("INTERVAL", _this.formdata.intervalTime);
                        }

                        _this.formdata.execTime = "";
                    } else if (val === 'E') {

                        _this.formdata.intervalTime = "";
                        _this.formdata.unit = "";
                        if (_this.formdata.execTime == null || _this.formdata.execTime === '') {
                            _this.setExpressValue("TIME", "00:00:00");
                        } else {
                            _this.setExpressValue("TIME", _this.formdata.execTime);
                        }

                    }
                },

                /**
                 * 点击树的结点，加载对应的数据
                 */
                nodeClickFn: function (nodeData, node, self) {
                    var _this = this;
                    var nodeApp = "";
                    _this.currentClickNode = nodeData;
                    if (nodeData.appCode != '0000') {
                        nodeApp = nodeData.appCode;
                        _this.nodeLeaf = true;
                        _this.appNameDisabled = true;
                        _this.searchFormdata.appName = nodeData.appName;
                        nodeApp = nodeData.appCode;
                    } else {
                        _this.nodeLeaf = false;
                        _this.appNameDisabled = false;
                        _this.searchFormdata.appName = '';
                    }

                    //var paramObj = {};

                    _this.searchFormdata.appCode = nodeApp;
                    var param = { condition: JSON.stringify(_this.searchFormdata) };
                    _this.$refs.refTable.remoteData(param);

                },


                /**
                 * 新增
                 */
                addFn: function () {
                    var _this = this;
                    _this.isReadOnly = false;
                    _this.dialogVisible = true;
                    _this.viewTitle = _this.viewTitleArrry[0];
                    _this.addFlag = true;
                    _this.isUdfFlag = true;
                    _this.isExecInterValFlag = false;
                    _this.isView = false;
                    _this.$nextTick(function () {
                        //_this.$refs.refForm.switch(_this.tableField[0].fields[1].field, 'disabled', false);
                        _this.$refs.refForm.resetFields();
                        _this.formdata.expression = " * * ? *";
                        _this.formdata.remark = "每天执行";
                        _this.formdata.appCode = _this.currentClickNode.appCode;
                        _this.formdata.appName = _this.currentClickNode.appName;
                        _this.formdata.configMethod = "1";
                        _this.formdata.execTimes = "11";
                        _this.formdata.execMethod = "E";
                        _this.setExpressValue("EXEC_TIMES", "11");
                        //disabeldone 由于手动生成的时候克隆表达式校验非常复杂，目前推荐自动生成
                        //_this.disabeldone = true;

                    });
                },

                viewDataFn: function (data) {
                    var _this = this;
                    _this.isReadOnly = true;
                    _this.viewTitle = _this.viewTitleArrry[2];
                    _this.dialogVisible = true;
                    _this.addFlag = false;
                    _this.refTemp = data;
                    _this.isView = true;

                    _this.$nextTick(function () {
                        yufp.clone(_this.refTemp, _this.formdata);
                        _this.formdata.startTime = _this.getDateFormStr(data.effectDate);
                        _this.formdata.endTime = _this.getDateFormStr(data.expireDate);
                        _this.formdata.expression = _this.refTemp.expression;
                    });
                },
                /**
                 * 修改
                 */
                modifyFn: function () {
                    var _this = this;
                    if (_this.$refs.refTable.selections.length != 1) {
                        _this.$message({ message: '请先选择一条记录', type: 'warning', duration: 6000 });
                        return;
                    }
                    _this.isReadOnly = true;
                    _this.viewTitle = _this.viewTitleArrry[1];
                    _this.dialogVisible = true;
                    _this.addFlag = false;
                    _this.refTemp = _this.$refs.refTable.selections[0];
                    _this.isView = false;
                    _this.$nextTick(function () {

                        yufp.clone(_this.refTemp, _this.formdata);

                        _this.formdata.startTime = _this.refTemp.effectDate;// _this.getDateFormStr(_this.refTemp.effectDate);
                        _this.formdata.endTime = _this.refTemp.expireDate; //_this.getDateFormStr(_this.refTemp.expireDate);
                        _this.formdata.expression = _this.refTemp.expression;



                    });
                },
                /**
                 * 删除
                 */
                deleteFn: function () {
                    var _this = this;
                    var selections = _this.$refs.refTable.selections;
                    if (selections.length != 1) {
                        _this.$message({ message: '请选择一条记录', type: 'warning', duration: 6000 });
                        return;
                    }

                    _this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                        duration: 6000,
                        center: true,
                        callback: function (action) {
                            if (action === 'confirm') {
                                yufp.service.request({
                                    method: 'DELETE',
                                    url: "api/use/plats/trigger/deleteUseTaskTimer",
                                    data: selections[0],
                                    callback: function (code, message, response) {
                                        if (response.code != 0) {
                                            isOk = false;
                                            _this.$message({ message: response.message, type: "warning" });
                                        } else {
                                            _this.$message('操作成功');
                                            _this.reloadData();

                                        }

                                    }
                                });
                            }
                        }
                    });
                },

                /** 自定义触发 验证器*/
                changeExecTimes: function (val) {
                    if (val != '') {
                        /*  if(this.formdata.execMethod==='E'){
                              this.setExpressValue("FIX_TIMES",val);
                          }else if(this.formdata.execMethod ==='I'){
                              this.setExpressValue("EXEC_TIMES",val);
                          }*/
                        this.setExpressValue("EXEC_TIMES", val);

                    }

                },



                setExpressValue: function (type, value) {

                    var _this = this;
                    let cronExpress = _this.formdata.expression;

                    if (cronExpress != null) {
                        let cronArray = cronExpress.trim().split(/\s+/);
                        let execTimesObj = _this.getExecTimesObj(_this.formdata.execTimes);

                        if (type === 'TIME') {
                            let timeArray = value.trim().split(/:/);
                            if (cronArray.length == 7) {
                                _this.formdata.expression = timeArray[2] + " " + timeArray[1] + " " + timeArray[0]
                                    + " " + cronArray[3] + " " + cronArray[4] + " " + cronArray[5] + " " + cronArray[6];
                            } else {
                                _this.formdata.expression = timeArray[2] + " " + timeArray[1] + " " + timeArray[0]
                                    + " " + cronArray[0] + " " + cronArray[1] + " " + cronArray[2] + " " + cronArray[3];
                            }
                            if (execTimesObj.key != null) {
                                _this.formdata.remark = execTimesObj.desc + value + "执行";
                            }

                        } else if (type === 'INTERVAL') {
                            let interValueDesc = "";
                            if (cronArray.length == 7) {
                                if (_this.formdata.unit === 'second') {
                                    interValueDesc = "秒"
                                    _this.formdata.expression = 0 + "/" + value + " " + "*" + " " + "*"
                                        + " " + cronArray[3] + " " + cronArray[4] + " " + cronArray[5] + " " + cronArray[6];
                                } else if (_this.formdata.unit === 'min') {
                                    interValueDesc = "分"
                                    _this.formdata.expression = 0 + " " + 0 + "/" + value + " " + "*"
                                        + " " + cronArray[3] + " " + cronArray[4] + " " + cronArray[5] + " " + cronArray[6];
                                } else if (_this.formdata.unit === 'hour') {
                                    interValueDesc = "时"
                                    _this.formdata.expression = 0 + " " + 0 + " " + 0 + "/" + value
                                        + " " + cronArray[3] + " " + cronArray[4] + " " + cronArray[5] + " " + cronArray[6];
                                } else {
                                    _this.formdata.expression = value + " " + value + " " + value
                                        + " " + cronArray[3] + " " + cronArray[4] + " " + cronArray[5] + " " + cronArray[6];
                                }


                            } else {
                                if (_this.formdata.unit === 'second') {
                                    interValueDesc = "秒"
                                    _this.formdata.expression = 0 + "/" + value + " " + "*" + " " + "*"
                                        + " " + cronArray[0] + " " + cronArray[1] + " " + cronArray[2] + " " + cronArray[3];
                                } else if (_this.formdata.unit === 'min') {
                                    interValueDesc = "分"
                                    _this.formdata.expression = 0 + " " + 0 + "/" + value + " " + "*"
                                        + " " + cronArray[0] + " " + cronArray[1] + " " + cronArray[2] + " " + cronArray[3];
                                } else if (_this.formdata.unit === 'hour') {
                                    interValueDesc = "时"
                                    _this.formdata.expression = 0 + " " + 0 + " " + 0 + + 0 + "/" + value
                                        + " " + cronArray[0] + " " + cronArray[1] + " " + cronArray[2] + " " + cronArray[3];
                                } else {
                                    _this.formdata.expression = value + " " + value + " " + value
                                        + " " + cronArray[0] + " " + cronArray[1] + " " + cronArray[2] + " " + cronArray[3];
                                }

                            }
                            _this.formdata.remark = execTimesObj.desc + "0点开始每隔" + value + interValueDesc + "执行";

                        } else if (type === 'EXEC_TIMES') {
                            let execTimesObj = _this.getExecTimesObj(value);
                            if (execTimesObj.key != null) {
                                if (cronArray.length == 7) {
                                    _this.formdata.expression = cronArray[0] + " " + cronArray[1] + " " + cronArray[2]
                                        + " " + execTimesObj.value;
                                } else {
                                    _this.formdata.expression = execTimesObj.value;
                                }

                                if (_this.formdata.execMethod === 'E') {//执行时间
                                    if (_this.formdata.execTime != '') {
                                        _this.formdata.remark = execTimesObj.desc + _this.formdata.execTime + "执行";
                                    }
                                } else if (_this.formdata.execMethod === 'I') {
                                    let unitDesc = "";
                                    if (_this.formdata.intervalTime != '') { //间隔时间
                                        if (_this.formdata.unit === 'second') {
                                            unitDesc = "秒";
                                        } else if (_this.formdata.unit === 'min') {
                                            unitDesc = "分";
                                        } else if (_this.formdata.unit === 'hour') {
                                            unitDesc = "时";
                                        }
                                    }
                                    _this.formdata.remark = execTimesObj.desc + "0点开始每隔"
                                        + _this.formdata.intervalTime + unitDesc + "执行";
                                } else {
                                    _this.formdata.remark = execTimesObj.desc;
                                }

                            }
                        }
                    }

                },

                getExecTimesObj: function (val) {
                    let retObject = {};
                    for (let i = 0; i < this.execTimesArrays.length; i++) {
                        if (val === this.execTimesArrays[i].key) {
                            retObject = this.execTimesArrays[i];
                            break;
                        }
                    }

                    return retObject;
                },



                checkTimeValidate: function (rule, value, callback) {
                    var reg = /^\d+$/;
                    if (this.formdata.unit == null ||
                        this.formdata.unit == "") {
                        if (value != null && value != '') {
                            this.$message({ message: "请先选择单位", type: "warning" });
                        } else {
                            callback();
                        }
                        //callback(new Error('请先选择单位'));
                        this.formdata.intervalTime = "";
                    } else if (value && !reg.test(value)) {
                        callback(new Error('数字类型错误'));
                    } else if (this.formdata.unit == "hour" && (value > 23 || value < 0)) {
                        callback(new Error('正确的值范围为[0,23]'));
                    } else if (value > 60 || value < 0) {
                        callback(new Error('正确的值范围为[0,60]'));
                    } else {
                        this.setExpressValue("INTERVAL", value);
                        callback();
                    }
                },

                checkDateTimeValidate: function (rule, value, callback) {
                    // var reg = /^(\d{2})(:)?(\d{2})\2(\d{2})$/;
                    var reg = /^(\d{2})(:)(\d{2})(:)(\d{2})$/;
                    if (value == null || value == '') {
                        callback();
                    } else {
                        var matchStr = value.match(reg);
                        if (value && !reg.test(value)) {
                            callback(new Error('正确的格式为:[hh:mm:ss]'));
                        } else if (matchStr[1] >= 24 || matchStr[3] >= 60 || matchStr[5] >= 60) {
                            callback(new Error('时间值范围不正确，请检查值范围'));
                        } else {
                            this.setExpressValue("TIME", value);
                            callback();
                        }
                    }
                },

                getStrFromDate: function (date) {
                    try {
                        var year = date.getFullYear();
                        var month = date.getMonth() + 1;
                        var strMonth = "";
                        var date = date.getDate();
                        var strDate = "";
                        if (month < 10) {
                            strMonth = "0" + month;
                        } else {
                            strMonth = "" + month;
                        }

                        if (date < 10) {
                            strDate = "0" + date;
                        } else {
                            strDate = "" + date;
                        }

                        return year + strMonth + strDate;
                    } catch (e) {
                        return "";
                    }
                },

                getDateFormStr: function (strDate) {
                    if (strDate != null && strDate.length == 8) {
                        try {
                            return new Date(parseInt(strDate.substr(0, 4)), parseInt(strDate.substr(4, 2)) - 1, parseInt(strDate.substr(6, 2)));
                        } catch (e) {

                            return null;
                        }

                    }
                    return null;
                }


            },

        });
    };
});